package com.rcclabs.remoteobjects;

//RC Labs Web Services

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Data {
	
	public String getCurrencyConversion(String fromCode, String toCode, String amount){
		String response = null;
		double result = 0;
		String currencyConversionRateString = "";
		
		try{
			URL url = new URL("http://www.webservicex.com/CurrencyConvertor.asmx/ConversionRate");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            PrintWriter out = new PrintWriter(connection.getOutputStream());

            String frmCur = "FromCurrency="+URLEncoder.encode(fromCode, "UTF-8");
            String toCur = "ToCurrency="+URLEncoder.encode(toCode, "UTF-8");

            out.println(frmCur+"&"+toCur);
            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            String data = "";
            while ((line = in.readLine()) != null) {
                  data = data + line;
            }
            in.close();
            
            if(!data.equals("") || data.contains("unavailable")==false){
            	currencyConversionRateString = extractValueFromXMLContent(data);
                
                double rate = Double.parseDouble(currencyConversionRateString);
    			result = rate * Double.parseDouble(amount);
    			
    			response = currencyConversionRateString+"-"+result;
            }
      	
		}
		catch(Exception ex){
			
		}
		return response;
	}

	public String getStockQuote(String symbol){
		String response = null;
		
		try{
			URL url = new URL("http://www.webservicex.net/stockquote.asmx/GetQuote");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            PrintWriter out = new PrintWriter(connection.getOutputStream());

            String symbolString = "symbol="+URLEncoder.encode(symbol, "UTF-8");
            
            out.println(symbolString);
            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            String data = "";
            while ((line = in.readLine()) != null) {
                  data = data + line;
            }
            in.close();
            
            if(!data.equals("") || data.contains("unavailable")==false){
            	String stockQuoteString = extractValueFromXMLContent(data);
                stockQuoteString = stockQuoteString.replace("&lt;", "<");
                stockQuoteString = stockQuoteString.replace("&gt;", ">");           
                stockQuoteString = buildXML(stockQuoteString);
                response = stockQuoteParseXML(stockQuoteString);
            }
            
        }    
        catch(Exception ex){
			
		}
		return response;
	}
	
	public String getDefinition(String wordToDefine){
	       String response = null;
	       try{
	    	    URL url = new URL("http://services.aonaware.com/DictService/DictService.asmx/DefineInDict");
	    	   	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setRequestMethod("POST");
	            connection.setDoOutput(true);
	            PrintWriter out = new PrintWriter(connection.getOutputStream());

	            String dictId = "dictId="+URLEncoder.encode("wn", "UTF-8");
	            String word = "word="+URLEncoder.encode(wordToDefine, "UTF-8");
	            out.println(dictId+"&"+word);
	            
	            out.close();

	            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            String line;
	            String data = "";
	            while ((line = in.readLine()) != null) {
	                  data = data + line;
	            }
	            in.close();

	            if(!data.equals("") || data.contains("unavailable")==false){
	            	response = data;
		            response = response.replaceAll("\\s+", " ");
		            response = definitionParseXML(response);
	            }
	            
	       }
	       catch(Exception ex){
	    	   ex.printStackTrace();
	       }
	       return response;
	}
	
	public String getThesaurus(String wordToDefine){
	       String response = null;
	       try{
	    	    URL url = new URL("http://words.bighugelabs.com/api/2/6f5766a796c020bea5dc5b10c9b2c1d9/"+wordToDefine+"/xml");
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setRequestMethod("POST");
	            connection.setDoOutput(true);
	            PrintWriter out = new PrintWriter(connection.getOutputStream());
	            out.close();

	            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            String line;
	            String data = "";
	            while ((line = in.readLine()) != null) {
	                  data = data + line;
	            }
	            in.close();
	            
	            if(!data.equals("") || data.contains("unavailable")==false){
	            	String response1 = data;
		            response = thesaurusParseAndBuildXML(response1);
	            }
	            
	       }
	       catch(Exception ex){
	    	   ex.printStackTrace();
	       }
	       return response;
	}
	
	public String getWeather(String zipcode, String dayf){
	    String response = "";
	    try{
	    	   URL url = new URL("http://xoap.weather.com/weather/local/"+zipcode+"?cc=*&dayf="+dayf+"&link=xoap&prod=xoap&par=1162236064"+"&key=5e27751578d4bd4f");
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setRequestMethod("POST");
	            connection.setDoOutput(true);
	            PrintWriter out = new PrintWriter(connection.getOutputStream());
	            out.close();

	            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            String line;
	            String data = "";
	            while ((line = in.readLine()) != null) {
	                  data = data + line;
	            }
	            in.close();

	            response = data;
	            response = response.replaceAll("\\s+", " ");
	       }
	       catch(Exception ex){
	    	   ex.printStackTrace();
	       }
	    return response;		
	}
	
	public String extractValueFromXMLContent(String xmlContent){
		String value = "";
		
		int c1 = 0;
        int c2 = 0;
        
		for(int i=0;i<xmlContent.length();i++){
            if(xmlContent.charAt(i)=='<'){
                  c1++;
            }
            if(xmlContent.charAt(i)=='>'){
                   c2++;
            }
            if((c1==2)&&(c2==2)&&(xmlContent.charAt(i)!='<')&&(xmlContent.charAt(i)!='>')){
            	value = value + xmlContent.charAt(i);
            }
        }
		
		return value;
	}
	
	public String buildXML(String content){
		String xmlcontent = "";
		xmlcontent = "<?xml version="+"\"1.0\""+"?>" + content;
		return xmlcontent;
	}
	
	public String stockQuoteParseXML(String xmlcontent){
		String response = "";
		try{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource inS = new InputSource();
	        inS.setCharacterStream(new StringReader(xmlcontent));
			Document doc = db.parse(inS);
			Element docEle = doc.getDocumentElement();
			
			NodeList List = docEle.getElementsByTagName("Stock");

			if (List != null && List.getLength() > 0) {
				for (int i = 0; i < List.getLength(); i++) {

					Node node = List.item(i);

					if (node.getNodeType() == Node.ELEMENT_NODE) {
						Element e = (Element) node;
						NodeList nodeList = e.getElementsByTagName("Symbol");
						response = response + "Symbol: "+nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("Name");
						response = response + "\n" + "Name: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("Last");
						response = response + "\n" + "Last: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("Date");
						response = response + "\n" + "Date: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("Time");
						response = response + "\n" + "Time: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("Change");
						response = response + "\n" + "Change: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("Open");
						response = response + "\n" + "Open: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("High");
						response = response + "\n" + "High: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("Low");
						response = response + "\n" + "Low: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("Volume");
						response = response + "\n" + "Volume: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("MktCap");
						response = response + "\n" + "MktCap: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("PreviousClose");
						response = response + "\n" + "PreviousClose: " + nodeList.item(0).getChildNodes().item(0).getNodeValue() + ",";
						
						nodeList = e.getElementsByTagName("PercentageChange");
						response = response + "\n" + "PercentageChange: " + nodeList.item(0).getChildNodes().item(0).getNodeValue() + ",";
						
						nodeList = e.getElementsByTagName("AnnRange");
						response = response + "\n" + "AnnRange: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("Earns");
						response = response + "\n" + "Earns: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("P-E");
						response = response + "\n" + "P-E: " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
					}
				}
			} 
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return response;
	}

	public String definitionParseXML(String xmlcontent){
		String response = "";
		try{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource inS = new InputSource();
	        inS.setCharacterStream(new StringReader(xmlcontent));
			Document doc = db.parse(inS);
			Element docEle = doc.getDocumentElement();
			
			NodeList List = docEle.getElementsByTagName("Definitions");

			if (List != null && List.getLength() > 0) {
				for (int i = 0; i < List.getLength(); i++) {

					Node node = List.item(i);

					if (node.getNodeType() == Node.ELEMENT_NODE) {
						Element e = (Element) node;
						NodeList nodeList = e.getElementsByTagName("Name");
						response = response + "Definition extracted from " + nodeList.item(0).getChildNodes().item(0).getNodeValue();
						
						nodeList = e.getElementsByTagName("WordDefinition");
						response = response + "\n" + "Definition: " + "\n" + nodeList.item(0).getChildNodes().item(0).getNodeValue();
					}
				}
			} 
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return response;
	}
	
	public String thesaurusParseAndBuildXML(String xmlcontent){
		String response = "<?xml version="+"\"1.0\""+" encoding="+"\"utf-8\""+"?>";
		
		try{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource inS = new InputSource();
	        inS.setCharacterStream(new StringReader(xmlcontent));
			Document doc = db.parse(inS);
			Element docEle = doc.getDocumentElement();
			
			response = response + "<words>";
			
			NodeList List = docEle.getElementsByTagName("w");

			if (List != null && List.getLength() > 0) {
				for (int i = 0; i < List.getLength(); i++) {
					Element el = (Element)List.item(i);		
					response = response + "<word>";
					
					response = response + "<value>"+List.item(i).getChildNodes().item(0).getNodeValue()+"</value>";
					
					response = response + "<punctuation>"+el.getAttribute("p")+"</punctuation>";
					
					response = response + "<type>"+el.getAttribute("r")+"</type>";
					response = response + "</word>";
				}
			} 
			
			response = response + "</words>";
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return response;
	}
}

